<template>
  <div class="order-item">
    <!-- 订单头部 -->
    <div class="order-header">
      <div class="header-left">
        <span class="order-number">订单号：{{ order.orderNo }}</span>
        <span class="order-time">创建时间：{{ formatDate(order.createTime) }}</span>
      </div>
      <div class="header-right">
        <span class="order-status" :class="`status-${order.status}`">
          {{ getStatusText(order.status) }}
        </span>
      </div>
    </div>
    
    <!-- 订单商品列表 -->
    <div class="order-products">
      <div 
        v-for="(product, index) in order.products" 
        :key="`${product.id}-${index}`"
        class="product-item"
      >
        <router-link :to="`/product/detail?id=${product.id}`" class="product-image">
          <img :src="product.image || '/default-product.png'" :alt="product.name" class="product-img">
        </router-link>
        <div class="product-info">
          <router-link :to="`/product/detail?id=${product.id}`" class="product-name">
            {{ product.name }}
          </router-link>
          <div v-if="product.specs && product.specs.length > 0" class="product-specs">
            <span v-for="spec in product.specs" :key="spec.name" class="spec-text">
              {{ spec.name }}: {{ spec.value }}
            </span>
          </div>
          <div class="product-price-quantity">
            <span class="product-price">¥{{ formatPrice(product.price) }}</span>
            <span class="product-quantity">x{{ product.quantity }}</span>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 订单收货信息 -->
    <div v-if="order.address" class="order-address">
      <div class="address-info">
        <span class="address-label">收货信息：</span>
        <span class="address-name">{{ order.address.name }} </span>
        <span class="address-phone">{{ order.address.phone }} </span>
        <span class="address-detail">{{ order.address.province }}{{ order.address.city }}{{ order.address.district }}{{ order.address.detail }}</span>
      </div>
    </div>
    
    <!-- 订单金额信息 -->
    <div class="order-amount">
      <div class="amount-details">
        <span class="amount-label">商品总价：</span>
        <span class="amount-value">¥{{ formatPrice(order.productAmount) }}</span>
      </div>
      <div class="amount-details">
        <span class="amount-label">运费：</span>
        <span class="amount-value">¥{{ formatPrice(order.freightAmount) }}</span>
      </div>
      <div v-if="order.couponAmount > 0" class="amount-details">
        <span class="amount-label">优惠券：</span>
        <span class="amount-value discount">-¥{{ formatPrice(order.couponAmount) }}</span>
      </div>
      <div class="amount-total">
        <span class="total-label">实付款：</span>
        <span class="total-value">¥{{ formatPrice(order.totalAmount) }}</span>
      </div>
    </div>
    
    <!-- 订单操作按钮 -->
    <div class="order-actions">
      <!-- 待付款 -->
      <template v-if="order.status === 'pendingPayment'">
        <button 
          @click="handleCancelOrder" 
          class="action-btn cancel-btn"
        >
          取消订单
        </button>
        <button 
          @click="handlePayOrder" 
          class="action-btn pay-btn"
        >
          立即支付
        </button>
      </template>
      
      <!-- 待发货 -->
      <template v-else-if="order.status === 'pendingShipment'">
        <button 
          @click="handleRemindShipment" 
          class="action-btn remind-btn"
        >
          提醒发货
        </button>
        <button 
          @click="handleContactSeller" 
          class="action-btn contact-btn"
        >
          联系客服
        </button>
      </template>
      
      <!-- 待收货 -->
      <template v-else-if="order.status === 'pendingReceipt'">
        <button 
          @click="handleCheckLogistics" 
          class="action-btn logistics-btn"
        >
          查看物流
        </button>
        <button 
          @click="handleConfirmReceipt" 
          class="action-btn confirm-btn"
        >
          确认收货
        </button>
      </template>
      
      <!-- 已完成 -->
      <template v-else-if="order.status === 'completed'">
        <button 
          @click="handleBuyAgain" 
          class="action-btn buy-again-btn"
        >
          再次购买
        </button>
        <button 
          @click="handleReview" 
          class="action-btn review-btn"
        >
          评价商品
        </button>
        <router-link 
          :to="`/user/order/detail?id=${order.id}`" 
          class="action-btn detail-btn"
        >
          查看详情
        </router-link>
      </template>
      
      <!-- 已取消 -->
      <template v-else-if="order.status === 'cancelled'">
        <button 
          @click="handleBuyAgain" 
          class="action-btn buy-again-btn"
        >
          再次购买
        </button>
        <button 
          @click="handleDeleteOrder" 
          class="action-btn delete-btn"
        >
          删除订单
        </button>
        <router-link 
          :to="`/user/order/detail?id=${order.id}`" 
          class="action-btn detail-btn"
        >
          查看详情
        </router-link>
      </template>
      
      <!-- 已退款 -->
      <template v-else-if="order.status === 'refunded'">
        <router-link 
          :to="`/user/order/detail?id=${order.id}`" 
          class="action-btn detail-btn"
        >
          查看详情
        </router-link>
      </template>
      
      <!-- 其他状态 -->
      <template v-else>
        <router-link 
          :to="`/user/order/detail?id=${order.id}`" 
          class="action-btn detail-btn"
        >
          查看详情
        </router-link>
      </template>
    </div>
    
    <!-- 退款进度条（如果有退款） -->
    <div v-if="order.refundStatus && order.refundStatus !== 'none'" class="refund-progress">
      <div class="refund-status">
        退款状态：{{ getRefundStatusText(order.refundStatus) }}
      </div>
      <div v-if="order.refundProgress && order.refundProgress.length > 0" class="progress-steps">
        <div 
          v-for="(step, index) in order.refundProgress" 
          :key="index"
          class="progress-step" 
          :class="{ 'progress-step-active': index <= order.currentRefundStep }"
        >
          <div class="step-dot"></div>
          <div class="step-line" v-if="index < order.refundProgress.length - 1"></div>
          <div class="step-text">{{ step.text }}</div>
          <div class="step-time">{{ formatDate(step.time) }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router'
import { useOrderStore } from '../../store/modules/order'
import { formatPrice, formatDate } from '../../utils/helper'
import { ElMessage } from 'element-plus'

const props = defineProps({
  // 订单数据
  order: {
    type: Object,
    required: true,
    default: () => ({
      id: '',
      orderNo: '',
      createTime: '',
      status: 'pendingPayment',
      products: [],
      address: {},
      productAmount: 0,
      freightAmount: 0,
      couponAmount: 0,
      totalAmount: 0,
      refundStatus: 'none'
    })
  },
  // 是否显示完整信息
  showFullInfo: {
    type: Boolean,
    default: true
  }
})

const router = useRouter()
const orderStore = useOrderStore()

// 获取订单状态文本
const getStatusText = (status) => {
  const statusMap = {
    pendingPayment: '待付款',
    pendingShipment: '待发货',
    pendingReceipt: '待收货',
    completed: '已完成',
    cancelled: '已取消',
    refunded: '已退款'
  }
  return statusMap[status] || status
}

// 获取退款状态文本
const getRefundStatusText = (status) => {
  const statusMap = {
    none: '无退款',
    applying: '退款申请中',
    approved: '退款已通过',
    rejected: '退款已拒绝',
    processing: '退款处理中',
    completed: '退款已完成'
  }
  return statusMap[status] || status
}

// 处理取消订单
const handleCancelOrder = () => {
  orderStore.cancelOrder(props.order.id).then(() => {
    ElMessage.success('订单已取消')
    // 触发父组件更新列表
    emit('orderUpdated')
  }).catch(error => {
    ElMessage.error('取消订单失败：' + error.message)
  })
}

// 处理支付订单
const handlePayOrder = () => {
  router.push({
    path: '/order/pay',
    query: { orderId: props.order.id }
  })
}

// 处理提醒发货
const handleRemindShipment = () => {
  orderStore.remindShipment(props.order.id).then(() => {
    ElMessage.success('已提醒商家发货')
  }).catch(error => {
    ElMessage.error('提醒发货失败：' + error.message)
  })
}

// 处理联系客服
const handleContactSeller = () => {
  ElMessage.info('正在连接客服...')
  // 实际项目中这里应该跳转到客服聊天页面
}

// 处理查看物流
const handleCheckLogistics = () => {
  router.push({
    path: '/order/logistics',
    query: { orderId: props.order.id }
  })
}

// 处理确认收货
const handleConfirmReceipt = () => {
  orderStore.confirmReceipt(props.order.id).then(() => {
    ElMessage.success('已确认收货')
    // 触发父组件更新列表
    emit('orderUpdated')
  }).catch(error => {
    ElMessage.error('确认收货失败：' + error.message)
  })
}

// 处理再次购买
const handleBuyAgain = () => {
  // 将订单中的商品添加到购物车
  const cartItems = props.order.products.map(product => ({
    id: product.id,
    name: product.name,
    image: product.image,
    price: product.price,
    quantity: product.quantity,
    skuId: product.skuId || 'default',
    specs: product.specs || []
  }))
  
  cartItems.forEach(item => {
    orderStore.addToCart(item)
  })
  
  ElMessage.success('商品已添加到购物车')
  router.push('/cart')
}

// 处理评价商品
const handleReview = () => {
  router.push({
    path: '/order/review',
    query: { orderId: props.order.id }
  })
}

// 处理删除订单
const handleDeleteOrder = () => {
  orderStore.deleteOrder(props.order.id).then(() => {
    ElMessage.success('订单已删除')
    // 触发父组件更新列表
    emit('orderDeleted')
  }).catch(error => {
    ElMessage.error('删除订单失败：' + error.message)
  })
}

// 定义事件
const emit = defineEmits(['orderUpdated', 'orderDeleted'])
</script>

<style scoped>
.order-item {
  background-color: #fff;
  border: 1px solid $border-color;
  border-radius: $border-radius-base;
  overflow: hidden;
  margin-bottom: 16px;
}

/* 订单头部 */
.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background-color: $bg-color;
  border-bottom: 1px solid $border-color;
}

.header-left {
  display: flex;
  gap: 20px;
}

.order-number,
.order-time {
  font-size: $font-size-sm;
  color: $text-color-secondary;
}

.order-status {
  font-size: $font-size-base;
  font-weight: 500;
  padding: 4px 12px;
  border-radius: $border-radius-small;
}

.status-pendingPayment {
  color: $warning-color;
  background-color: rgba(250, 173, 20, 0.1);
}

.status-pendingShipment {
  color: $primary-color;
  background-color: rgba(59, 130, 246, 0.1);
}

.status-pendingReceipt {
  color: $info-color;
  background-color: rgba(14, 165, 233, 0.1);
}

.status-completed {
  color: $success-color;
  background-color: rgba(34, 197, 94, 0.1);
}

.status-cancelled {
  color: $text-color-placeholder;
  background-color: rgba(156, 163, 175, 0.1);
}

.status-refunded {
  color: $danger-color;
  background-color: rgba(239, 68, 68, 0.1);
}

/* 订单商品列表 */
.order-products {
  padding: 16px;
}

.product-item {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid $border-color;
}

.product-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.product-image {
  flex: 0 0 80px;
  height: 80px;
  border-radius: $border-radius-base;
  overflow: hidden;
}

.product-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info {
  flex: 1;
  min-width: 0;
}

.product-name {
  font-size: $font-size-base;
  color: $text-color;
  line-height: 1.4;
  margin-bottom: 8px;
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  text-decoration: none;
}

.product-name:hover {
  color: $primary-color;
}

.product-specs {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 8px;
}

.spec-text {
  font-size: $font-size-xs;
  color: $text-color-placeholder;
}

.product-price-quantity {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-price {
  font-size: $font-size-base;
  color: $danger-color;
  font-weight: 500;
}

.product-quantity {
  font-size: $font-size-sm;
  color: $text-color-secondary;
}

/* 订单收货信息 */
.order-address {
  padding: 16px;
  background-color: $bg-color;
  border-top: 1px solid $border-color;
  border-bottom: 1px solid $border-color;
}

.address-info {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.address-label {
  font-size: $font-size-sm;
  color: $text-color-secondary;
}

.address-name,
.address-phone,
.address-detail {
  font-size: $font-size-sm;
  color: $text-color;
}

/* 订单金额信息 */
.order-amount {
  padding: 16px;
  text-align: right;
}

.amount-details {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.amount-label {
  font-size: $font-size-sm;
  color: $text-color-secondary;
}

.amount-value {
  font-size: $font-size-sm;
  color: $text-color;
}

.amount-value.discount {
  color: $danger-color;
}

.amount-total {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 12px;
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid $border-color;
}

.total-label {
  font-size: $font-size-base;
  color: $text-color-secondary;
}

.total-value {
  font-size: $font-size-lg;
  color: $danger-color;
  font-weight: bold;
}

/* 订单操作按钮 */
.order-actions {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background-color: $bg-color;
  border-top: 1px solid $border-color;
  flex-wrap: wrap;
}

.action-btn {
  padding: 8px 16px;
  border: 1px solid $border-color;
  background-color: #fff;
  color: $text-color;
  font-size: $font-size-sm;
  cursor: pointer;
  border-radius: $border-radius-base;
  transition: all 0.3s;
  text-decoration: none;
}

.action-btn:hover {
  color: $primary-color;
  border-color: $primary-color;
}

.cancel-btn:hover {
  color: $text-color-placeholder;
  border-color: $border-color;
}

.pay-btn {
  color: #fff;
  background-color: $primary-color;
  border-color: $primary-color;
}

.pay-btn:hover {
  color: #fff;
  background-color: $primary-color-dark;
  border-color: $primary-color-dark;
}

.remind-btn:hover {
  color: $info-color;
  border-color: $info-color;
}

.contact-btn:hover {
  color: $success-color;
  border-color: $success-color;
}

.logistics-btn:hover {
  color: $primary-color;
  border-color: $primary-color;
}

.confirm-btn {
  color: #fff;
  background-color: $success-color;
  border-color: $success-color;
}

.confirm-btn:hover {
  color: #fff;
  background-color: $success-color-dark;
  border-color: $success-color-dark;
}

.buy-again-btn:hover {
  color: $primary-color;
  border-color: $primary-color;
}

.review-btn {
  color: #fff;
  background-color: $warning-color;
  border-color: $warning-color;
}

.review-btn:hover {
  color: #fff;
  background-color: $warning-color-dark;
  border-color: $warning-color-dark;
}

.detail-btn:hover {
  color: $primary-color;
  border-color: $primary-color;
}

.delete-btn:hover {
  color: $danger-color;
  border-color: $danger-color;
}

/* 退款进度 */
.refund-progress {
  padding: 16px;
  background-color: $bg-color;
  border-top: 1px solid $border-color;
}

.refund-status {
  font-size: $font-size-base;
  color: $danger-color;
  margin-bottom: 16px;
}

.progress-steps {
  display: flex;
  justify-content: space-between;
  position: relative;
}

.progress-step {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  flex: 1;
  z-index: 1;
}

.progress-step-active .step-dot {
  background-color: $primary-color;
}

.progress-step-active .step-line {
  background-color: $primary-color;
}

.progress-step-active .step-text {
  color: $text-color;
  font-weight: 500;
}

.progress-step-active .step-time {
  color: $text-color-secondary;
}

.step-dot {
  width: 12px;
  height: 12px;
  background-color: $border-color;
  border-radius: 50%;
  margin-bottom: 8px;
  position: relative;
  z-index: 2;
}

.step-line {
  position: absolute;
  top: 6px;
  left: 100%;
  width: 100%;
  height: 2px;
  background-color: $border-color;
  z-index: 0;
}

.step-text {
  font-size: $font-size-sm;
  color: $text-color-placeholder;
  margin-bottom: 4px;
  text-align: center;
}

.step-time {
  font-size: $font-size-xs;
  color: $text-color-placeholder;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .order-header {
    padding: 12px;
  }
  
  .header-left {
    gap: 15px;
  }
  
  .order-products,
  .order-address,
  .order-amount,
  .order-actions {
    padding: 12px;
  }
}

@media (max-width: 992px) {
  .order-item {
    margin-bottom: 12px;
  }
  
  .product-item {
    gap: 12px;
    margin-bottom: 12px;
    padding-bottom: 12px;
  }
  
  .product-image {
    flex: 0 0 60px;
    height: 60px;
  }
  
  .product-specs {
    gap: 8px;
  }
  
  .action-btn {
    padding: 6px 12px;
    font-size: $font-size-xs;
  }
}

@media (max-width: 768px) {
  .order-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .header-left {
    flex-direction: column;
    gap: 5px;
  }
  
  .order-products,
  .order-address,
  .order-amount,
  .order-actions {
    padding: 10px;
  }
  
  .amount-details,
  .amount-total {
    justify-content: space-between;
  }
  
  .order-actions {
    justify-content: center;
    gap: 8px;
  }
  
  .progress-steps {
    flex-direction: column;
    gap: 16px;
  }
  
  .progress-step {
    flex-direction: row;
    align-items: center;
    gap: 12px;
  }
  
  .step-line {
    position: static;
    width: 20px;
    height: 2px;
  }
}

@media (max-width: 480px) {
  .product-item {
    gap: 10px;
  }
  
  .product-image {
    flex: 0 0 50px;
    height: 50px;
  }
  
  .order-actions {
    flex-direction: column;
  }
  
  .action-btn {
    width: 100%;
  }
}
</style>